<?php
namespace Application\Controller;

use Application\Model\Dao\UpdateDao;
use Application\Service\EmailService;
use Application\Service\XmlService;
use Zend\Authentication\AuthenticationService;
use Zend\Math\Rand;
use Zend\View\Model\ViewModel;
use Zend\View\Model\JsonModel;
use Application\Service\ImageService;
use Application\Service\UpdateService;

class PeopleController extends LoginAwareController
{

    /**
     * @return JsonModel
     * Get all discussion data.
     */
    public function saveDiscussion()
    {
        $request = $this->getRequest();
        if ($request->isPost()) {
            $discussion = $request->getPost('dicussion');
            $title = $request->getPost('title');
            $targetType = $request->getPost('targetType');
            $targetId = $request->getPost('targetId');
            $photoSet = $this->getUploadedFileXml('attached');
            $loginId = $this->getLoggedinUserId();
            $updateDao =  $this->getServiceLocator()->get('update');
            $updateDao->saveUpdateData($discussion, $loginId, $photoSet, null, UpdateDao::$UPDATE_TYPE['DISCUSSION'], $targetType, $targetId);
            $data = array(
                'result' => 'success'
            );
            return new JsonModel($data);
        }
    }

    public function searchPeopleAction(){
	    $req = $this->getRequest();
	    $name = $req->getQuery('name');
	    $userDao = $this->getServiceLocator()->get('user');
	    $users = $userDao->searchUserByName($name, $this->getUsersGroup());
	    return new JsonModel($users);
    }

    public function getLoggedInAction(){

        $userDao = $this->getServiceLocator()->get('user');
        $users = $userDao->getAllLoggedinUser($this->getUsersGroup(), $this->getLoggedinUserId());
        return new JsonModel($users);
    }


    public function saveUserAction(){

        $request = $this->getRequest();
        if ($request->isPost()) {
            $chatId = $request->getPost('chatId');

            $userDao = $this->getServiceLocator()->get('user');
            $users = $userDao->saveLoggedinUser($this->getLoggedinUserId(), $chatId);

            $data = array(
                'result' => 'success'
            );
            return new JsonModel($data);
        }
    }

    public function getBlockPeopleAction(){
        $userDao = $this->getServiceLocator()->get('user');
        $users = $userDao->getAllGroupMates($this->getUsersBlockId());
        return new JsonModel($users);
    }

    public function getApartmentPeopleAction(){
        $userDao = $this->getServiceLocator()->get('user');
        $users = $userDao->getAllGroupMates($this->getUsersApartmentId());
        return new JsonModel($users);
    }

    public function advSearchAction(){
        $req = $this->getRequest();
        $name = $req->getQuery('name');
        $flat = $req->getQuery('flatNo');
        $profession = $req->getQuery('profession');
        $post = $req->getQuery('post');
        $userDao = $this->getServiceLocator()->get('user');
        $users = $userDao->searchUserByAll($name, $flat, $profession, $post,$this->getUsersGroup());
        return new JsonModel($users);
    }

    public function getLoggedUserAction(){
        return new JsonModel($this->getUserFromSession());
    }


    public function sendInvitationAction(){

        $request = $this->getRequest();
        if ($request->isPost()) {
            $emailIds = $request->getPost('email');
            $emailService = new EmailService();
            $userDao = $this->getServiceLocator()->get('user');
            $user = $this->getUserFromSession();

            $emailArray = explode(',', $emailIds);

            foreach($emailArray as $email){
                $secret = Rand::getString(10);
                $result = $userDao->inviteUser($email, $user->id, $secret);
               if($result == null) {
                   $emailService->sendInvitationEmail($user->email, $email, $secret, $user->id, $user->name);
               }
                $data = array(
                    'result' => 'success'
                );
               return new JsonModel($data);
            }
            $data = array(
                'result' => 'success'
            );
            return new JsonModel($data);
        }
    }


    public function blockAction(){

        $request = $this->getRequest();
        if ($request->isPost()) {
            $userId = $request->getPost('id');
            $reason = $request->getPost('reason');
            $emailService = new EmailService();



            $userDao = $this->getServiceLocator()->get('user');

            $blockedUser = $userDao->getUserByIdWithGroup($userId);

            if($this->isFromSameGroup($blockedUser, $this->getUserFromSession())){
                $blockCount = $userDao->getBlockCount($userId);

                $population = $userDao->getGroupMatesCount($this->getUsersBlockId());


                if($population < ($blockCount + 1 )*2){

                    $userDao->blockUser($blockedUser->id);
                    $emailService->sendBlockedEmail($blockedUser->email, $blockCount, $population);
                    // send that you are block now.
                    // send the procedure to get yourself unblocked.
                    $data = array(
                        'result' => 'success'
                    );

                    return new JsonModel($data);
                } else {
                    $userDao->blockedAction( $this->getLoggedinUserId(), $blockedUser->id, $reason );
                }
                $emailService->sendBlockingEmail($blockedUser->email, $blockCount + 1, $population);


                $data = array(
                    'result' => 'success'
                );

                return new JsonModel($data);
            } else {
                $data = array(
                    'result' => 'nopermission'
                );

                return new JsonModel($data);
            }
        }
    }

    private function getBlockOfUser($user){
        $groups = $user->groups;
        if($groups){
            foreach($groups as $group ){
                if($group['type'] === 'block') {
                    return $group['id'];
                }
            }
        }
        return 0;
    }

    private function getApartmentOfUser($user){
        $groups = $user->groups;
        if($groups){
            foreach($groups as $group ){
                if($group['type'] === 'apartment') {
                    return $group['id'];
                }
            }
        }
        return 0;
    }


    private function isFromSameGroup($firstUser, $secondUser){
        return $this->getApartmentOfUser($firstUser) == $this->getApartmentOfUser($secondUser);
    }

    public function profileAction()
    {
        $userDao = $this->getServiceLocator ()
            ->get ( 'user' );

        $req = $this->getRequest();
        $id = $req->getQuery('id');

        $user = $userDao->getUserByIdWithGroup($id);
        if($this->isFromSameGroup($user, $this->getUserFromSession())){
            $layout = $this->layout()->setVariable('user', $this->getUserFromSession());
            $layout->setTemplate('layout/loggedin');
            $view = new ViewModel(array('user' => $user, 'curUser' => $this->getUserFromSession() ) );
            $view->setTemplate('/application/user/profile');
            return $view;
        } else {
            $layout = $this->layout()->setVariable('user', $this->getUserFromSession());
            $layout->setTemplate('layout/loggedin');
            $view = new ViewModel(array('user' => 'nopermission', 'curUser' => $this->getUserFromSession() ) );
            $view->setTemplate('/application/user/profile');
        }
    }



    public function saveChatAction(){
        $request = $this->getRequest();
        if ($request->isPost()) {
            $chatId = $request->getPost('chat');
            $fromId = $request->getPost('from');
            $toID = $request->getPost('to');

            $userDao = $this->getServiceLocator()->get('user');
            $users = $userDao->saveChat($fromId, $toID, $chatId);
            $data = array(
                'result' => 'success'
            );
            return new JsonModel($data);
        }
    }


    public function getChatAction(){
        $request = $this->getRequest();
        $oneUser = $request->getQuery('one');
        $secondUser = $request->getQuery('second');

        $userDao = $this->getServiceLocator()->get('user');
        $users = $userDao->getChat($oneUser, $secondUser);

        return new JsonModel($users);
    }

}

?>
